#include "cJSON/cJSON.h"
#include "log/log.h"
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    // 1. 生成json字符串  {"name":"tom"，"age":12}
    char *name = "tom";
    int age = 12;
    // 创建一个空的cJSON对象
    cJSON * cjson_obj = cJSON_CreateObject();
    // 向对象中添加键值对
    cJSON_AddStringToObject(cjson_obj, "name", name);
    cJSON_AddNumberToObject(cjson_obj, "age", age);
    // 将cJSON对象转换为字符串
    char *json = cJSON_PrintUnformatted(cjson_obj);
    log_debug("生成json字符串：%s", json);

    // 2. 解析json字符串
    cJSON *root_obj = cJSON_Parse(json);
    cJSON *name_obj = cJSON_GetObjectItem(root_obj, "name");
    cJSON *age_obj = cJSON_GetObjectItem(root_obj, "age");
    if (name_obj == NULL || age_obj == NULL)
    {
        log_error("json中没有name或age键");
        return -1;
    }
    char *name2 = name_obj->valuestring;
    int age2 = age_obj->valueint;
    log_debug("解析json字符串：name=%s, age=%d", name2, age2);

    // 3. 释放内存
    cJSON_Delete(cjson_obj);
    cJSON_Delete(root_obj);
    free(json);

    return 0;
}
